import axios from 'axios'
import store from '../store';
import router from '../router'
axios.defaults.timeout = 60000;
axios.defaults.baseURL = 'http://www.jdyuewan.com/platform/';  // http://www.jdyuewan.com/platform/     'http://132.232.13.213:8081/
// axios.defaults.headers = ("ContentType","application/json;charset=UTF-8")
axios.interceptors.request.use(function (config) {
    return config;
}, function (error) {
    Message.error({
        message: '加载超时'
    });
    return Promise.reject(error);
});

// 添加请求拦截器
axios.interceptors.request.use(
    config => {
        if(store.state.token){
        config.headers.token = `${store.state.token}`
        }
        return config
    },
    err => {
        return Promise.reject(err)
    }
)
// 添加响应拦截器
axios.interceptors.response.use(
  response => {
    if(response.data.code == 401){
        router.replace({ //跳转到登录页面
            path: '/',
        });
    }else if(response.data.code == 402){
        router.replace({ //跳转到登录页面
            path: '/',
        });
    }
    return response;
  },
  error => { //默认除了2XX之外的都是错误的，就会走这里
    // if(error.response){
    //   switch(error.response.code){
    //     case 401:
    //       store.dispatch('UserLogout'); //可能是token过期，清除它
    //       router.replace({ //跳转到登录页面
    //         path: '/login',
    //         query: { redirect: router.currentRoute.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
    //       });
    //   }
    // }
    // return Promise.reject(error.response);
  }
);

export default {
    post(url,data,callback) {
        return axios.post(url, data,callback).then(function (response) {
            callback(response.data)
        }).catch((error) => {
            callback(error)
        })
    },

    get(url, data,callback) {
        return axios.get(url, data,callback).then(function (response) {
            callback(response.data)
        }).catch((error) => {
            callback(error)
        })
    },
    put(url, params, callback) {
        return axios.put(url, params ,callback) .then(function (response) {
            callback(response.data)
        }).catch((error) => {
            callback(error)
        })

        return axios.put(url, params ,callback) .then(function (response) {
            callback(response.data)
        }).catch((error) => {
            callback(error)
        })

        return axios.put(url, params, callback).then(function (response) {
            callback(response.data)
        }).catch((error) => {
            callback(error)
        })

    },
    delete(url, params, callback) {
        return axios.delete(url, params, callback).then(function (response) {
            callback(response.data);
        }).catch((error) => {
            callback(error)
        })
    },
    patch(url,params,callback){
        return axios.patch(url,params,callback).then(function (response) {
        callback(response.data);
        }).catch((error) => {
        callback(error)
        })
    }
}
